//
//  MLSMainController.swift
//  MLSMircoBlog
//
//  Created by 袁航 on 15/7/27.
//  Copyright © 2015年 yuanhang. All rights reserved.
//

import UIKit

class MLSMainController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加子控制器
        addChildViewControllers()
        
    }
    
    
    //MARK:- 当时图显示出来后,添加按钮
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 添加按钮(控制器中底部导航栏上对应的item是懒加载的,在视图显示完毕的时候,才会加载,如果提前添加按钮,会被item覆盖)
        addComposeBtn()
    }
    
    //MARK:- 添加子控制器
    private func addChildViewControllers() {
        addChildViewController(MLSHomeController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MLSMessageController(), title: "消息", imageName: "tabbar_message_center")
        
        // 占位控制器(用来摆放中间按钮)
        addChildViewController(UIViewController())
        addChildViewController(MLSDiscoverController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(MLSProfileController(), title: "我", imageName: "tabbar_profile")
    }
    
    //MARK:- 添加compose发送按钮
    private func addComposeBtn() {

        // 计算位置和大小
        let btnW = tabBar.bounds.width / CGFloat(childViewControllers.count)
        let btnH = tabBar.bounds.height
        let rect = CGRect(x: 0, y: 0, width: btnW, height: btnH)
        
        // 设置按钮的位置
        composeBtn.frame = CGRectOffset(rect, 2 * btnW, 0)
    }
    
    //MARK:- 按钮中央点击事件(通过消息循环机制传递信息,不能加(private)用私有方法)
    func composeBtnClick() {
        let composeVC = MLSComposeController()
        let nav = UINavigationController(rootViewController: composeVC)
        presentViewController(nav, animated: true, completion: nil)
    }
    
    //MARK:- 添加视图控制器
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        // 设置标题
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        // 嵌入导航控制器
        let nav = UINavigationController(rootViewController: vc)
        // 加入tabBar控制器
        addChildViewController(nav)
    }
    
    //MARK:- 懒加载控件
    private lazy var composeBtn: UIButton = {
        
        let btn = UIButton()
        
        // 设置图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        // 按钮点击事件
        btn.addTarget(self, action: "composeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 添加到tabBar上
        self.tabBar.addSubview(btn)
        
        return btn
    }()
}
